package com.screen.screendisplay.service.impl.electric;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.screen.screendisplay.entity.electric.ElectricProdoperPowerGeneral;
import com.screen.screendisplay.mapper.electric.ElectricProdoperPowerGeneralMapper;
import com.screen.screendisplay.service.electric.ElectricProdoperPowerGeneralService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.screen.screendisplay.vo.electric.FdComplateTrend;
import com.screen.screendisplay.vo.electric.FdPlanCompletionStatus;
import com.screen.screendisplay.vo.electric.FdPowerPlantSupplyComplateStatus;
import com.screen.screendisplay.vo.wholeproduct.AnnualPowerGenerationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 发电情况详情表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class ElectricProdoperPowerGeneralServiceImpl extends ServiceImpl<ElectricProdoperPowerGeneralMapper, ElectricProdoperPowerGeneral> implements ElectricProdoperPowerGeneralService {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    /**
     * 发电计划完成情况
     * @param year
     * @param month
     * @return
     */
    @Override
    public FdPlanCompletionStatus fdPlanCompletionStatus(Integer year, Integer month) {
        LambdaQueryWrapper<ElectricProdoperPowerGeneral> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ElectricProdoperPowerGeneral::getYear, year)
                .eq(ElectricProdoperPowerGeneral::getMonth, month);
        List<ElectricProdoperPowerGeneral> dataList = this.list(lqw);
        FdPlanCompletionStatus status = new FdPlanCompletionStatus();
        status.setYear(year);
        status.setMonth(month);
        status.setMonthlyPlanPower(BigDecimal.valueOf(
                dataList.stream().mapToDouble(item ->
                        item.getMonthlyPlanPower().doubleValue()).sum()));
        status.setMonthlyActualPower(BigDecimal.valueOf(
                dataList.stream().mapToDouble(item ->
                        item.getMonthlyActualPower().doubleValue()).sum()
        ));
        status.setMonthlyCompletionRate(BigDecimal.valueOf(
                dataList.stream().mapToDouble(item ->
                        item.getMonthlyCompletionRate().doubleValue()).sum()
        ));
        status.setMonthlyOverShortage(BigDecimal.valueOf(
                dataList.stream().mapToDouble(item ->
                        item.getMonthlyOverShortage().doubleValue()).sum()
        ));
        status.setAnnualPlanPower(BigDecimal.valueOf(
                dataList.stream().mapToDouble(item ->
                        item.getAnnualPlanPower().doubleValue()).sum()
        ));
        status.setAnnualActualPower(BigDecimal.valueOf(
                dataList.stream().mapToDouble(item ->
                        item.getAnnualActualPower().doubleValue()).sum()
        ));
        status.setAnnualCompletionRate(BigDecimal.valueOf(
                dataList.stream().mapToDouble(item ->
                        item.getAnnualCompletionRate().doubleValue()).sum()
        ));
        status.setAnnualOverShortage(BigDecimal.valueOf(
                dataList.stream().mapToDouble(item ->
                        item.getAnnualOverShortage().doubleValue()).sum()
        ));
        return status;
    }

    /**
     * 发电量完成趋势
     * @param year 年份
     * @return
     */
    @Override
    public List<FdComplateTrend> fdComplateTrend(Integer year) {
        List<FdComplateTrend> result = new ArrayList<>();
        
        // 查询当前年和去年的数据
        Integer lastYear = year - 1;
        
        // 构建去年的数据
        FdComplateTrend lastYearTrend = new FdComplateTrend();
        lastYearTrend.setYear(lastYear);
        setMonthlyDataFromDb(lastYearTrend, lastYear);
        result.add(lastYearTrend);
        
        // 构建今年的数据
        FdComplateTrend currYearTrend = new FdComplateTrend();
        currYearTrend.setYear(year);
        setMonthlyDataFromDb(currYearTrend, year);
        result.add(currYearTrend);
        
        return result;
    }
    
    /**
     * 从数据库查询并设置月度数据
     * @param trend ComplateTrend对象
     * @param year 年份
     */
    private void setMonthlyDataFromDb(FdComplateTrend trend, Integer year) {
        String sql = "SELECT month, " +
                    "SUM(monthly_actual_power) as total_actual_power " +
                    "FROM qt_dp_electric_prodoper_power_general " +
                    "WHERE year = ? " +
                    "GROUP BY month " +
                    "ORDER BY month";
        
        List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, year);
        
        for (Map<String, Object> row : results) {
            Integer month = (Integer) row.get("month");
            BigDecimal totalActualPower = (BigDecimal) row.get("total_actual_power");
            
            switch (month) {
                case 1:
                    trend.setMth_1(totalActualPower);
                    break;
                case 2:
                    trend.setMth_2(totalActualPower);
                    break;
                case 3:
                    trend.setMth_3(totalActualPower);
                    break;
                case 4:
                    trend.setMth_4(totalActualPower);
                    break;
                case 5:
                    trend.setMth_5(totalActualPower);
                    break;
                case 6:
                    trend.setMth_6(totalActualPower);
                    break;
                case 7:
                    trend.setMth_7(totalActualPower);
                    break;
                case 8:
                    trend.setMth_8(totalActualPower);
                    break;
                case 9:
                    trend.setMth_9(totalActualPower);
                    break;
                case 10:
                    trend.setMth_10(totalActualPower);
                    break;
                case 11:
                    trend.setMth_11(totalActualPower);
                    break;
                case 12:
                    trend.setMth_12(totalActualPower);
                    break;
            }
        }
    }
    
    /**
     * 各个电厂供电完成情况
     * @param year 年份
     * @return 电厂供电完成情况列表
     */
    @Override
    public List<FdPowerPlantSupplyComplateStatus> fdPowerPlantSupplyComplateStatus(Integer year) {
        String sql = "SELECT " +
                    "power_plant_code, " +
                    "power_plant_name, " +
                    "MAX(annual_plan_power) as annual_plan_power, " +
                    "MAX(annual_actual_power) as annual_actual_power " +
                    "FROM qt_dp_electric_prodoper_power_general " +
                    "WHERE year = ? " +
                    "GROUP BY power_plant_code, power_plant_name " +
                    "ORDER BY power_plant_code";
        
        List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, year);
        
        List<FdPowerPlantSupplyComplateStatus> result = new ArrayList<>();
        for (Map<String, Object> row : results) {
            FdPowerPlantSupplyComplateStatus status = new FdPowerPlantSupplyComplateStatus();
            status.setYear(year);
            status.setPowerPlantCode((String) row.get("power_plant_code"));
            status.setPowerPlantName((String) row.get("power_plant_name"));
            status.setAnnualPlanPower((BigDecimal) row.get("annual_plan_power"));
            status.setAnnualActualPower((BigDecimal) row.get("annual_actual_power"));
            result.add(status);
        }
        return result;
    }

    /**
     * 获取年度发电完成情况（最近5年）
     * @return 年度发电完成情况列表
     */
    @Override
    public List<AnnualPowerGenerationVO> getAnnualPowerGeneration() {
        // 从数据库查询年度汇总数据
        List<ElectricProdoperPowerGeneral> annualStatsList = baseMapper.getAnnualPowerGenerationStats();
        
        // 转换为VO对象
        List<AnnualPowerGenerationVO> resultList = new ArrayList<>();
        for (ElectricProdoperPowerGeneral entity : annualStatsList) {
            AnnualPowerGenerationVO vo = new AnnualPowerGenerationVO();
            vo.setYear(entity.getYear());
            vo.setAnnualPlanPower(entity.getAnnualPlanPower());
            vo.setAnnualActualPower(entity.getAnnualActualPower());
            
            // 计算完成率：实际发电量 / 计划发电量 * 100
            if (entity.getAnnualPlanPower() != null && 
                entity.getAnnualPlanPower().compareTo(BigDecimal.ZERO) != 0) {
                BigDecimal completionRate = entity.getAnnualActualPower()
                        .divide(entity.getAnnualPlanPower(), 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"))
                        .setScale(2, RoundingMode.HALF_UP);
                vo.setAnnualCompletionRate(completionRate);
            } else {
                vo.setAnnualCompletionRate(BigDecimal.ZERO);
            }
            
            resultList.add(vo);
        }
        
        return resultList;
    }
}